#include "market_data/market_data_manager.h"
#include <spdlog/spdlog.h>
#include <algorithm>

namespace hft {

MarketDataManager::MarketDataManager(
    std::shared_ptr<MarketDataReceiver> receiver,
    std::shared_ptr<AsyncMarketDataStorage> storage,
    std::shared_ptr<MarketDataMonitor> monitor)
    : receiver_(receiver), storage_(storage), monitor_(monitor) {
}

MarketDataManager::~MarketDataManager() {
    stop();
}

bool MarketDataManager::initialize() {
    if (!receiver_ || !storage_ || !monitor_) {
        spdlog::error("MarketDataManager: Invalid components");
        return false;
    }
    
    // 注册市场数据回调
    receiver_->registerCallback([this](const MarketDataMessage& data) {
        handleMarketData(data);
    });
    
    return true;
}

bool MarketDataManager::start() {
    if (running_) {
        spdlog::warn("MarketDataManager: Already running");
        return false;
    }
    
    // 启动维护线程
    running_ = true;
    maintenance_thread_ = std::thread(&MarketDataManager::maintenanceThreadFunc, this);
    
    // 重新订阅所有合约
    std::lock_guard<std::mutex> lock(subscription_mutex_);
    if (!subscribed_symbols_.empty()) {
        if (!receiver_->subscribe(subscribed_symbols_)) {
            spdlog::error("MarketDataManager: Failed to resubscribe symbols");
            stop();
            return false;
        }
    }
    
    spdlog::info("MarketDataManager: Started");
    return true;
}

void MarketDataManager::stop() {
    if (!running_) {
        return;
    }
    
    // 停止维护线程
    {
        std::lock_guard<std::mutex> lock(maintenance_mutex_);
        running_ = false;
    }
    maintenance_cv_.notify_one();
    
    if (maintenance_thread_.joinable()) {
        maintenance_thread_.join();
    }
    
    // 取消所有订阅
    std::lock_guard<std::mutex> lock(subscription_mutex_);
    if (!subscribed_symbols_.empty()) {
        receiver_->unsubscribe(subscribed_symbols_);
        subscribed_symbols_.clear();
    }
    
    spdlog::info("MarketDataManager: Stopped");
}

int MarketDataManager::subscribe(const std::vector<std::string>& symbols) {
    if (symbols.empty()) {
        return 0;
    }
    
    std::lock_guard<std::mutex> lock(subscription_mutex_);
    
    // 过滤已订阅的合约
    std::vector<std::string> new_symbols;
    for (const auto& symbol : symbols) {
        if (std::find(subscribed_symbols_.begin(), subscribed_symbols_.end(), symbol) 
            == subscribed_symbols_.end()) {
            new_symbols.push_back(symbol);
        }
    }
    
    if (new_symbols.empty()) {
        return 0;
    }
    
    // 订阅新合约
    if (!receiver_->subscribe(new_symbols)) {
        spdlog::error("MarketDataManager: Failed to subscribe symbols");
        return 0;
    }
    
    // 更新订阅列表
    subscribed_symbols_.insert(subscribed_symbols_.end(), 
                             new_symbols.begin(), new_symbols.end());
    
    spdlog::info("MarketDataManager: Subscribed {} symbols", new_symbols.size());
    return new_symbols.size();
}

int MarketDataManager::unsubscribe(const std::vector<std::string>& symbols) {
    if (symbols.empty()) {
        return 0;
    }
    
    std::lock_guard<std::mutex> lock(subscription_mutex_);
    
    // 过滤未订阅的合约
    std::vector<std::string> to_unsubscribe;
    for (const auto& symbol : symbols) {
        auto it = std::find(subscribed_symbols_.begin(), subscribed_symbols_.end(), symbol);
        if (it != subscribed_symbols_.end()) {
            to_unsubscribe.push_back(symbol);
            subscribed_symbols_.erase(it);
        }
    }
    
    if (to_unsubscribe.empty()) {
        return 0;
    }
    
    // 取消订阅
    if (!receiver_->unsubscribe(to_unsubscribe)) {
        spdlog::error("MarketDataManager: Failed to unsubscribe symbols");
        return 0;
    }
    
    spdlog::info("MarketDataManager: Unsubscribed {} symbols", to_unsubscribe.size());
    return to_unsubscribe.size();
}

std::vector<std::string> MarketDataManager::getSubscribedSymbols() const {
    std::lock_guard<std::mutex> lock(subscription_mutex_);
    return subscribed_symbols_;
}

MarketDataMessage MarketDataManager::getLatestMarketData(
    const std::string& symbol) const {
    std::lock_guard<std::mutex> lock(data_mutex_);
    auto it = latest_data_.find(symbol);
    if (it != latest_data_.end()) {
        return it->second;
    }
    return MarketDataMessage{};
}

std::vector<MarketDataMessage> MarketDataManager::queryHistoricalData(
    const std::string& symbol,
    const std::chrono::system_clock::time_point& start_time,
    const std::chrono::system_clock::time_point& end_time) const {
    
    // 直接使用存储组件查询
    auto storage = std::dynamic_pointer_cast<MarketDataStorage>(storage_);
    if (!storage) {
        spdlog::error("MarketDataManager: Invalid storage component");
        return {};
    }
    
    return storage->query(symbol, start_time, end_time);
}

int MarketDataManager::registerMarketDataCallback(
    std::function<void(const MarketDataMessage&)> callback) {
    if (!callback) {
        return 0;
    }
    
    std::lock_guard<std::mutex> lock(callback_mutex_);
    int id = next_callback_id_++;
    callbacks_[id] = std::move(callback);
    return id;
}

bool MarketDataManager::unregisterMarketDataCallback(int callback_id) {
    std::lock_guard<std::mutex> lock(callback_mutex_);
    return callbacks_.erase(callback_id) > 0;
}

std::unordered_map<std::string, MarketDataMonitor::Statistics> 
MarketDataManager::getDataQualityReport() const {
    std::unordered_map<std::string, MarketDataMonitor::Statistics> report;
    
    std::lock_guard<std::mutex> lock(subscription_mutex_);
    for (const auto& symbol : subscribed_symbols_) {
        report[symbol] = monitor_->getStatistics(symbol);
    }
    
    return report;
}

uint64_t MarketDataManager::getStorageStats() const {
    return storage_->getStorageStats();
}

int MarketDataManager::cleanupOldData(int days) {
    if (days <= 0) {
        return 0;
    }
    
    auto storage = std::dynamic_pointer_cast<MarketDataStorage>(storage_);
    if (!storage) {
        spdlog::error("MarketDataManager: Invalid storage component");
        return 0;
    }
    
    auto cutoff_time = std::chrono::system_clock::now() - 
                      std::chrono::hours(24 * days);
    return storage->cleanup(cutoff_time);
}

void MarketDataManager::handleMarketData(const MarketDataMessage& data) {
    // 更新最新数据缓存
    {
        std::lock_guard<std::mutex> lock(data_mutex_);
        latest_data_[data.symbol] = data;
    }
    
    // 监控数据质量
    monitor_->onMarketData(data);
    
    // 存储数据
    storage_->store(data);
    
    // 触发回调
    std::lock_guard<std::mutex> lock(callback_mutex_);
    for (const auto& [id, callback] : callbacks_) {
        try {
            callback(data);
        } catch (const std::exception& e) {
            spdlog::error("MarketDataManager: Callback error: {}", e.what());
        }
    }
}

void MarketDataManager::maintenanceThreadFunc() {
    const int CHECK_INTERVAL_SECONDS = 60;  // 每分钟检查一次
    
    while (running_) {
        {
            std::unique_lock<std::mutex> lock(maintenance_mutex_);
            maintenance_cv_.wait_for(lock, 
                std::chrono::seconds(CHECK_INTERVAL_SECONDS),
                [this] { return !running_; });
        }
        
        if (!running_) {
            break;
        }
        
        // 检查数据质量
        std::lock_guard<std::mutex> lock(subscription_mutex_);
        for (const auto& symbol : subscribed_symbols_) {
            if (!monitor_->checkDataQuality(symbol)) {
                spdlog::warn("MarketDataManager: Poor data quality for {}", symbol);
                
                // 可以在这里添加重订阅逻辑
                std::vector<std::string> to_resubscribe = {symbol};
                if (receiver_->unsubscribe(to_resubscribe) && 
                    receiver_->subscribe(to_resubscribe)) {
                    spdlog::info("MarketDataManager: Resubscribed {}", symbol);
                }
            }
        }
        
        // 检查存储队列
        size_t queue_size = storage_->getQueueSize();
        if (queue_size > 10000) {  // 队列过长警告阈值
            spdlog::warn("MarketDataManager: Storage queue size: {}", queue_size);
        }
    }
}

} // namespace hft